package com.hyl.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.hyl.common.to.mq.OrderTo;
import com.hyl.common.to.mq.StockDetailTo;
import com.hyl.common.to.mq.StockLockedTo;
import com.hyl.common.utils.R;
import com.hyl.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.hyl.gulimall.ware.entity.WareOrderTaskEntity;
import com.hyl.gulimall.ware.service.WareSkuService;
import com.hyl.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author hyl_marco
 * @data 2022/5/26 - 14:46
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存解锁场景
     * 1.订单成功
     * i.下单成功，订单过期没有支付被系统自动取消或用户手动取消
     * ii. 下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，锁定的库存需要自动解锁
     * 2.订单不成功
     * i.锁库存失败
     * <p>
     * 1和2的区别在于2本来锁库存就失败了，无需再解锁。而1锁库存成功，在有其他业务失败的情况下需要解锁
     * 如何判断1需不需要解锁呢，根据订单的状态
     *
     * !!!如果解锁库存的消息失败，一定要告诉服务解锁失败。（手动确认机制）
     * @param
     * @return
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 监听订单超时释放后发来的库存解锁消息
     * @param orderTo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo,Message message,Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存");
        try{
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
